import type { MaybeRefOrGetter } from 'vue'
import { merge } from 'lodash-es'
import { defaultNumber } from '@/utils'

export function useChartToolboxDataView(
  props?: MaybeRefOrGetter<{
    optionToContent?: (opt: any, g: (d: any) => string | HTMLElement) => string | HTMLElement
    dataViewFirstCellName?: string
  }>,
) {
  const option = toValue(props) || {}
  const dataView = ref({
    readOnly: true,
    optionToContent(opt: any) {
      // console.log(opt);
      if (option.optionToContent) {
        return option.optionToContent(opt, generateTable)
      }
      const axisData = opt.xAxis?.[0]?.data || []
      const series = opt.series || []
      const data = [
        [option.dataViewFirstCellName || '', ...series.map((v: any) => v.name)],
        ...(axisData || []).map((v: any, i: number) => [v, ...series.map((s: any) => defaultNumber(s.data[i]))]),
      ]
      // console.log(data);
      return generateTable(data)
    },
    backgroundColor: 'var(--el-bg-color)',
    textColor: 'var(--el-text-color-regular)',
  })

  function generateTable(data: any[] = []) {
    const theadData = data[0] || []
    const tbodyData = data.slice(1) || []
    let table = '<table class="chart-internal-table">'
    let thead = '<thead class="chart-internal-table-thead">'
    for (const item of theadData) {
      thead += `<th>${item ?? '-'}</th>`
    }
    thead += '</thead>'

    let tbody = '<tbody class="chart-internal-table-tbody">'
    for (const row of tbodyData) {
      tbody += `<tr>${row.map((item: any) => `<td>${item ?? '-'}</td>`).join('')}</tr>`
    }
    tbody += '</tbody>'
    table += `${thead + tbody}</table>`
    return table
  }

  function getChartToolboxDataView(option = {}) {
    return merge({}, unref(dataView), option)
  }

  return {
    dataView,
    generateTable,
    getChartToolboxDataView,
  }
}
